const apiBaseUrl = '/api/image';
let currentPage = 1;
let totalPages = 1;
let selectedBase64 = '';
window.addEventListener('DOMContentLoaded', () => {
    const params = new URLSearchParams(window.location.search);
    const image = params.get('image');
    if (image === '1') {
        document.querySelectorAll('.upload-btn').forEach(btn => {
            btn.style.display = 'inline-block';
        });
    } else {
        document.querySelectorAll('.upload-btn').forEach(btn => {
            btn.style.display = 'none';
        });
    }
});

window.addEventListener('DOMContentLoaded', () => {
    const previewImage = document.getElementById('previewImage');
    previewImage.addEventListener('wheel', function (event) {
        event.preventDefault();

        let scale = parseFloat(previewImage.dataset.scale) || 1;
        const delta = event.deltaY;

        if (delta < 0) {
            scale += 0.1;
        } else {
            scale -= 0.1;
        }

        scale = Math.min(Math.max(0.5, scale), 5);

        previewImage.style.transform = `scale(${scale})`;
        previewImage.dataset.scale = scale;
    });
    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
            const imageModal = document.getElementById('imagePreviewModal');
            if (imageModal && imageModal.style.display !== 'none') {
                closePreview();
            }
            const types = ['single', 'folder', 'zip']; // 根据你页面的实际类型写
            types.forEach(type => {
                const modal = document.getElementById(`upload-${type}-modal`);
                if (modal && modal.style.display !== 'none') {
                    closeUploadModal(type);
                }
            });
            const searchModal = document.getElementById('search-modal');
            if (searchModal && searchModal.style.display !== 'none') {
                closeSearchModal();
            }
        }
    });
});


function getCsrfTokenFromCookie() {
    const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/);
    return match ? decodeURIComponent(match[1]) : null;
}
function secureFetch(url, options = {}) {
    const token = getCsrfTokenFromCookie();
    const headers = options.headers || {};
    if (token) {
        headers['X-XSRF-TOKEN'] = token;
    }
    return fetch(url, { ...options, headers });
}
function handleFileChange(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function (e) {
        selectedBase64 = e.target.result.split(',')[1]; // 去掉 data:image/jpeg;base64, 前缀
    };
    reader.readAsDataURL(file);
}

function previewSelectedImage() {
    if (!selectedBase64) {
        alert('请先选择图片文件');
        return;
    }
    showPreview(selectedBase64);
}

// 打开上传模态框
function openUploadModal(type) {
    document.getElementById(`upload-${type}-modal`).style.display = 'block';
}

function showPreview(data) {
    const previewImage = document.getElementById('previewImage');

    if (data instanceof File) {
        const reader = new FileReader();
        reader.onload = function(e) {
            previewImage.src = e.target.result;
        };
        reader.readAsDataURL(data);
    } else {
        // 传的是 base64 字符串
        previewImage.src = `data:image/jpeg;base64,${data}`;
    }

    previewImage.style.transform = 'scale(1)';
    previewImage.dataset.scale = 1;

    document.getElementById('imagePreviewModal').style.display = 'flex';
}


// 关闭预览
function closePreview() {
    const modal = document.getElementById('imagePreviewModal');
    modal.style.display = 'none';

    const previewImage = document.getElementById('previewImage');
    previewImage.src = '';
    previewImage.style.transform = '';
    previewImage.dataset.scale = 1;
}



// 关闭上传模态框
function closeUploadModal(type) {
    document.getElementById(`upload-${type}-modal`).style.display = 'none';
    document.getElementById(`message-${type}-modal`).className = 'alert';
    document.getElementById(`message-${type}-modal`).textContent = '';
}

// 打开搜索相似图片模态框
function openSearchModal() {
    document.getElementById('search-modal').style.display = 'block';
}

// 关闭搜索相似图片模态框
function closeSearchModal() {
    document.getElementById('search-modal').style.display = 'none';
    document.getElementById('message-search-modal').className = 'alert';
    document.getElementById('message-search-modal').textContent = '';
    document.getElementById('results-modal').innerHTML = '';
}

function uploadSingleImage(type) {
    const fileInput = document.getElementById(`file-${type}-modal`);
    const messageDiv = document.getElementById(`message-${type}-modal`);
    const resultsList = document.getElementById('single-upload-modal');

    // 清除旧的消息
    messageDiv.className = '';
    messageDiv.textContent = '';

    if (!fileInput.files || fileInput.files.length === 0) {
        messageDiv.className = 'alert alert-danger';
        messageDiv.textContent = '请选择一个文件';
        return;
    }

    const file = fileInput.files[0];


    showLoading();
    const formData = new FormData();
    formData.append('file', file);

    secureFetch(`${apiBaseUrl}/upload/single`, {
        method: 'POST',
        body: formData
    })
        .then(response => response.text())
        .then(text => {
            messageDiv.className = 'alert alert-success';
            messageDiv.textContent = `上传成功 ` + text;
        })
        .catch(error => {
            messageDiv.className = 'alert alert-danger';
            messageDiv.textContent = `上传失败: ${error.message}`;
        })
        .finally(() => {
            hideLoading();
        });
}


function uploadFolderImage(type) {
    const fileInput = document.getElementById(`file-${type}-modal`);
    const files = fileInput.files;
    const messageDiv = document.getElementById(`message-${type}-modal`);

    if (files.length === 0) {
        messageDiv.className = 'alert alert-danger';
        messageDiv.textContent = '请选择一个文件夹';
        return;
    }


    showLoading();
    const formData = new FormData();

    // 遍历文件夹中的所有文件
    for (let i = 0; i < files.length; i++) {
        formData.append('files[]', files[i]);
    }

    secureFetch(`${apiBaseUrl}/upload/folder`, {
        method: 'POST',
        body: formData
    })
        .then(response => response.text())
        .then(data => {
            messageDiv.className = 'alert alert-success';
            messageDiv.textContent = data;
            closeUploadModal(type);
            alert("上传文件成功");
        })
        .catch(error => {
            messageDiv.className = 'alert alert-danger';
            messageDiv.textContent = error.message;
        })
        .finally(() => {
            hideLoading();
        });
}


function searchSingleImages(type) {
    const fileInput = document.getElementById(`file-${type}-modal`);
    const messageDiv = document.getElementById(`message-${type}-modal`);
    const resultsList = document.getElementById('single-upload-modal');

    // 清除旧的消息
    messageDiv.className = '';
    messageDiv.textContent = '';

    if (!fileInput.files || fileInput.files.length === 0) {
        messageDiv.className = 'alert alert-danger';
        messageDiv.textContent = '请选择一个文件';
        return;
    }
    showLoading()
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);

    secureFetch(`${apiBaseUrl}/SearchSingleImages`, {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            // 确保 data 是数组
            if (!Array.isArray(data)) {
                console.error("data 不是数组:", data);
                messageDiv.className = 'alert alert-danger';
                messageDiv.textContent = '搜索结果格式错误';
                return;
            }
            messageDiv.className = 'alert alert-success';
            messageDiv.textContent = '搜索成功';
            resultsList.innerHTML = '';
            data.forEach(item => {
                const li = document.createElement('li');
                const img = document.createElement('img');
                img.src = `data:image/jpeg;base64,${item.entity.image}`;
                img.alt = item.entity.name;
                img.style.cursor = 'pointer'; // 鼠标变小手
                img.onclick = () => showPreview(item.entity.image); // 添加点击事件
                const scoreSpan = document.createElement('span');
                scoreSpan.textContent = `差异度: ${item.score.toFixed(2)}`;
                li.appendChild(img);
                li.appendChild(document.createTextNode(item.entity.name));
                li.appendChild(scoreSpan);
                resultsList.appendChild(li);
            });
        })
        .catch(error => {
            messageDiv.className = 'alert alert-danger';
            messageDiv.textContent = error.message;
        }).finally(() => {
        hideLoading()
    });
}

function uploadZipFile(type) {
    const fileInput = document.getElementById(`file-${type}-modal`);
    const file = fileInput.files[0];
    const messageDiv = document.getElementById(`message-${type}-modal`);

    if (!file) {
        messageDiv.className = 'alert alert-danger';
        messageDiv.textContent = '请选择一个文件';
        return;
    }


    showLoading();
    const formData = new FormData();
    formData.append('file', file);

    secureFetch(`${apiBaseUrl}/upload/zip`, {
        method: 'POST',
        body: formData
    })
        .then(response => response.text())
        .then(data => {
            messageDiv.className = 'alert alert-success';
            messageDiv.textContent = data;
            closeUploadModal(type);
            fetchImages();
        })
        .catch(error => {
            messageDiv.className = 'alert alert-danger';
            messageDiv.textContent = error.message;
        })
        .finally(() => {
            hideLoading();
        });
}


function searchImages(type) {
    const fileInput = document.getElementById(`file-${type}-modal`);
    const file = fileInput.files[0];
    const topK = document.getElementById('topK-modal').value;
    const messageDiv = document.getElementById(`message-${type}-modal`);
    const resultsList = document.getElementById('results-modal');

    if (!file) {
        messageDiv.className = 'alert alert-danger';
        messageDiv.textContent = '请选择一个文件';
        return;
    }

    showLoading();

    const formData = new FormData();
    formData.append('file', file);
    formData.append('topK', topK);

    const reader = new FileReader();
    reader.onload = function () {
        const originalImgSrc = reader.result;

        secureFetch(`${apiBaseUrl}/search`, {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                messageDiv.className = 'alert alert-success';
                messageDiv.textContent = '搜索成功';
                resultsList.innerHTML = '';

                // 创建标题行
                resultsList.appendChild(createResultRow('原图', '匹配图', '匹配图片名称', '差异度', true));

                data.forEach(item => {
                    const originalImg = createImage(originalImgSrc, file.name, () => showPreview(file));
                    const matchedImg = createImage(`data:image/jpeg;base64,${item.entity.image}`, item.entity.name, () => showPreview(item.entity.image));

                    const nameSpan = document.createElement('div');
                    nameSpan.textContent = item.entity.name;

                    const scoreSpan = document.createElement('div');
                    scoreSpan.textContent = `差异度: ${item.score.toFixed(2)}`;
                    resultsList.appendChild(createResultRow(originalImg, matchedImg, nameSpan,  scoreSpan));
                });
            })
            .catch(error => {
                console.error('搜索失败:', error);
                messageDiv.className = 'alert alert-danger';
                messageDiv.textContent = '搜索失败：' + error.message;
            })
            .finally(() => {
                hideLoading();
            });
    };

    reader.readAsDataURL(file);
}

// 创建单行结果（支持标题/内容）
function createResultRow(original, match, name, score, isHeader = false) {
    const row = document.createElement('li');
    row.className = 'search-result';
    row.style.display = 'flex';
    row.style.alignItems = 'center';
    row.style.marginBottom = '10px';

    [original, match, name, score].forEach(item => {
        const span = document.createElement('span');
        span.style.display = 'inline-block';
        span.style.width = '200px';
        span.style.textAlign = 'center';
        span.style.marginRight = '20px';
        if (isHeader) span.style.fontWeight = 'bold';

        if (item instanceof HTMLElement) {
            span.appendChild(item);
        } else {
            span.textContent = item;
        }

        row.appendChild(span);
    });

    return row;
}

// 创建图片元素
function createImage(src, alt, onClick) {
    const img = document.createElement('img');
    img.src = src;
    img.alt = alt;
    img.style.cursor = 'pointer';
    img.className = 'search-image';
    img.onclick = onClick;
    return img;
}



// 获取图片列表
function fetchImages(page = 1) {
    const nameInput = document.getElementById('search-name');

    const pageIndexInput = document.getElementById('pageIndex');
    const pageSizeInput = document.getElementById('pageSize');
    const name = nameInput.value;
    const pageIndex = page;
    const pageSize = parseInt(pageSizeInput.value);
    const imageListItems = document.getElementById('image-list-items');
    const pageInfo = document.getElementById('page-info');
    const firstPageBtn = document.getElementById('first-page');
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');
    const lastPageBtn = document.getElementById('last-page');

    const req = {
        name,
        pageIndex,
        pageSize,
    };
    showLoading();
    secureFetch(`${apiBaseUrl}/page`, {
        method: 'POST',
        body: JSON.stringify(req),
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            imageListItems.innerHTML = '';
            data.data.forEach(image => {
                const li = document.createElement('li');

                // 创建一个容器，包住勾选框和图片
                const container = document.createElement('div');
                container.style.display = 'flex';
                container.style.alignItems = 'center';
                container.style.marginBottom = '10px';

                // 勾选框
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'image-checkbox';
                checkbox.dataset.name = image.name;
                checkbox.dataset.image = image.image;
                checkbox.style.marginRight = '50px'; // 图片与勾选框的间距

                // 图片
                const img = document.createElement('img');
                img.src = `data:image/jpeg;base64,${image.image}`;
                img.alt = image.name;
                img.style.display = 'block';
                img.style.cursor = 'pointer'; // 鼠标变小手
                img.onclick = () => showPreview(image.image); // 添加点击事件

                container.appendChild(checkbox);
                container.appendChild(img);

                // 添加容器和图片名
                li.appendChild(container);
                const timeText = document.createElement('div');
                timeText.textContent = image.uploadDate;
                timeText.style.paddingLeft = '30px'; // 与图片对齐
                li.appendChild(timeText);

                const nameText = document.createElement('div');
                nameText.textContent = image.name;
                nameText.style.paddingLeft = '30px'; // 与图片对齐
                li.appendChild(nameText);

                imageListItems.appendChild(li);
            });

            // 分页信息更新
            totalPages = data.totalPages;
            currentPage = pageIndex;

            pageInfo.innerHTML = `
              <div>第 ${currentPage} 页 / 共 ${totalPages} 页</div>
              <div style="text-align:center;">共 ${data.totalRecords} 笔</div>
            `;
            console.log(typeof totalPages+totalPages);
            console.log(typeof currentPage+currentPage);
            firstPageBtn.disabled = (currentPage <= 1);
            prevPageBtn.disabled = (currentPage <= 1);
            nextPageBtn.disabled = (currentPage >= totalPages);
            lastPageBtn.disabled = (currentPage >= totalPages);

            pageIndexInput.value = currentPage;
        })
        .catch(error => {
            alert(error.message);
        }).finally(() => {
        hideLoading();
    });
}

// 删除图片
function batchDelete() {
    const checkboxes = document.querySelectorAll('.image-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('请先勾选要删除的图片');
        return;
    }
    showLoading();
    const names = Array.from(checkboxes).map(cb => cb.dataset.name);
    const isConfirmed = confirm(`确定要删除以下图片吗？\n\n${names.join('\n')}`);
    if (!isConfirmed) {
        hideLoading();
        return;
    }

    const req = {
        names: names  // 假设后端接受 name 数组参数
    };

    secureFetch(`${apiBaseUrl}/upload/deleteBatch`, {
        method: 'POST',
        body: JSON.stringify(req),
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.text())
        .then(data => {
            alert(data);
            fetchImages(currentPage); // 重新加载图片列表
        })
        .catch(error => {
            alert(error.message);
        }).finally(() => {
        hideLoading();
    });

}

// function downloadImage(base64Image, imageName) {
//     const link = document.createElement('a');
//     link.href = `data:image/jpeg;base64,${base64Image}`;
//     link.download = imageName;  // 设置下载的文件名
//     link.click();  // 自动点击下载
// }

async function batchDownload() {
    const checkboxes = document.querySelectorAll('.image-checkbox:checked');

    if (checkboxes.length === 0) {
        alert('请先勾选要下载的图片');
        return;
    }

    const zip = new JSZip();
    const folder = zip.folder("images"); // 可选：放进 images 子文件夹

    checkboxes.forEach((checkbox, index) => {
        const base64 = checkbox.dataset.image;
        const name = checkbox.dataset.name || `image_${index + 1}.jpg`;

        // 去除 base64 前缀
        const base64Content = base64.replace(/^data:image\/(png|jpeg);base64,/, "");

        folder.file(name, base64Content, {base64: true});
    });

    const content = await zip.generateAsync({type: "blob"});
    saveAs(content, "images.zip"); // 调用一次浏览器下载
}

function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'flex';
}

function hideLoading() {
    document.getElementById('loadingSpinner').style.display = 'none';
}

